﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


using System.Windows.Forms;
using System.Data.SQLite;


using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;

namespace Project
{
    public partial class Form1: Form
    {
        private float _currentZoom = 1.0f;
        private Size _originalImageSize;
        private Bitmap _originalImage; // 添加原始图像引用
        private bool _isDragging = false;
        private Point _dragStartPoint;
        private Bitmap _loadedImage;
        private Bitmap _imageBeforeFilter; // 当前图像未加滤镜的版本
        private bool _isSelecting = false;
        private Point _selectionStart;
        private Rectangle _selectionRectangle;
        private bool _isDrawingMode = false;
        private bool _isDrawing = false;
        private Point _lastPoint;
        private Bitmap _drawingLayer; // 用于绘画的临时图层

        public Form1()
        {
            InitializeComponent();
            pictureBox1.MouseWheel += PictureBox1_MouseWheel;
            pictureBox1.MouseDown += PictureBox1_MouseDown;
            pictureBox1.MouseMove += PictureBox1_MouseMove;
            pictureBox1.MouseUp += PictureBox1_MouseUp;
            pictureBox1.Paint += PictureBox1_Paint;
            // 启用 PictureBox 接收鼠标事件（重要）
            pictureBox1.MouseEnter += (s, e) => pictureBox1.Focus();
            DatabaseHelper.InitializeDatabase();
            LoadImageHistory();
            historyListBox.Visible = false;
            btnToggleHistory.Text = "显示历史记录";

        }


        private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
        {
            // 首先检查绘画模式 - 必须在其他事件之前
            if (_isDrawingMode)
            {
                if (e.Button == MouseButtons.Left)
                {
                    // 只处理绘画，不处理拖动
                    _isDrawing = true;
                    // 坐标转换（考虑缩放）
                    float scaleX = (float)_originalImage.Width / pictureBox1.Width;
                    float scaleY = (float)_originalImage.Height / pictureBox1.Height;
                    _lastPoint = new Point((int)(e.X * scaleX), (int)(e.Y * scaleY));
                }
                return; // 在绘画模式下不处理其他操作
            }

            // 以下是原有代码（非绘画模式下的操作）
            if (e.Button == MouseButtons.Left && pictureBox1.Image != null)
            {
                _isDragging = true;
                _dragStartPoint = e.Location;
                pictureBox1.Cursor = Cursors.Hand;
            }
            else if (e.Button == MouseButtons.Right && pictureBox1.Image != null)
            {
                _isSelecting = true;
                _selectionStart = e.Location;
                _selectionRectangle = new Rectangle();
                pictureBox1.Invalidate(); // 刷新以触发绘制选框
            }
        }

        private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
        {

            if (_isDragging)
            {
                Point newLocation = pictureBox1.Location;
                newLocation.X += e.X - _dragStartPoint.X;
                newLocation.Y += e.Y - _dragStartPoint.Y;
                pictureBox1.Location = newLocation;
            }
            else if (_isSelecting)
            {
                int x = Math.Min(_selectionStart.X, e.X);
                int y = Math.Min(_selectionStart.Y, e.Y);
                int width = Math.Abs(_selectionStart.X - e.X);
                int height = Math.Abs(_selectionStart.Y - e.Y);

                _selectionRectangle = new Rectangle(x, y, width, height);
                pictureBox1.Invalidate(); // 重绘 PictureBox 触发 Paint 绘制虚线框
            }
            if (pictureBox1.Image is Bitmap bmp)
            {
                float scaleX = (float)bmp.Width / pictureBox1.Width;
                float scaleY = (float)bmp.Height / pictureBox1.Height;

                int imgX = (int)(e.X * scaleX);
                int imgY = (int)(e.Y * scaleY);

                if (imgX >= 0 && imgY >= 0 && imgX < bmp.Width && imgY < bmp.Height)
                {
                    Color color = bmp.GetPixel(imgX, imgY);
                    toolStripStatusLabel2.Text = $"X:{imgX} Y:{imgY} | 颜色: R{color.R} G{color.G} B{color.B}";
                }
            }
            if (_isDrawingMode && _isDrawing)
            {
                // 坐标转换（考虑缩放）
                float scaleX = (float)_originalImage.Width / pictureBox1.Width;
                float scaleY = (float)_originalImage.Height / pictureBox1.Height;
                int imgX = (int)(e.X * scaleX);
                int imgY = (int)(e.Y * scaleY);

                if (_drawingLayer != null)
                {
                    using (Graphics g = Graphics.FromImage(_drawingLayer))
                    {
                        Pen pen = new Pen(Color.Red, 5); // 加粗笔触
                        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        g.DrawLine(pen, _lastPoint, new Point(imgX, imgY));
                    }
                    _lastPoint = new Point(imgX, imgY);
                    pictureBox1.Invalidate();
                }
                return; // 在绘画模式下不处理其他操作
            }


        }

        private void PictureBox1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _isDragging = false;
                pictureBox1.Cursor = Cursors.Default;
            }
            else if (e.Button == MouseButtons.Right)
            {
                _isSelecting = false;
                CropSelectedArea(); // 鼠标右键释放时执行裁剪
            }
            if (_isDrawingMode)
            {
                if (e.Button == MouseButtons.Left)
                {
                    _isDrawing = false;
                }
                return; // 在绘画模式下不处理其他操作
            }

        }
        private void PictureBox1_Paint(object sender, PaintEventArgs e)
        {
            if (_isSelecting && _selectionRectangle != Rectangle.Empty)
            {
                using (Pen pen = new Pen(Color.Red, 2))
                {
                    pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash;
                    e.Graphics.DrawRectangle(pen, _selectionRectangle);
                }
            }

            // 添加绘图层显示
            if (_isDrawingMode && _drawingLayer != null)
            {
                // 考虑缩放比例
                float scaleX = (float)pictureBox1.Width / _originalImage.Width;
                float scaleY = (float)pictureBox1.Height / _originalImage.Height;

                e.Graphics.DrawImage(_drawingLayer,
                    new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height),
                    new Rectangle(0, 0, _drawingLayer.Width, _drawingLayer.Height),
                    GraphicsUnit.Pixel);
            }
        }
        private void PictureBox1_MouseWheel(object sender, MouseEventArgs e)
        {
            if (ModifierKeys == Keys.Control) // 按住Ctrl键滚动
            {
                if (e.Delta > 0)
                {
                    ZoomIn();
                }
                else
                {
                    ZoomOut();
                }
            }
        }
        private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void clearButton_Click(object sender, EventArgs e)
        {
            pictureBox1.Image = null;
        }
        private void CropSelectedArea()
        {
            if (_originalImage == null || _selectionRectangle.Width == 0 || _selectionRectangle.Height == 0)
                return;
            _imageBeforeFilter?.Dispose();
            _imageBeforeFilter = new Bitmap(_originalImage);
            // 考虑缩放比例
            float scale = (float)_originalImage.Width / pictureBox1.Width;

            Rectangle actualRect = new Rectangle(
                (int)(_selectionRectangle.X * scale),
                (int)(_selectionRectangle.Y * scale),
                (int)(_selectionRectangle.Width * scale),
                (int)(_selectionRectangle.Height * scale)
            );

            Bitmap cropped = new Bitmap(actualRect.Width, actualRect.Height);
            using (Graphics g = Graphics.FromImage(cropped))
            {
                g.DrawImage(_originalImage, new Rectangle(0, 0, cropped.Width, cropped.Height), actualRect, GraphicsUnit.Pixel);
            }

            pictureBox1.Image?.Dispose();
            _originalImage?.Dispose();

            pictureBox1.Image = new Bitmap(cropped);
            _originalImage = new Bitmap(cropped);
            _originalImageSize = _originalImage.Size;

            ApplyZoom();
            UpdateStatus("裁剪成功");
        }

        private void showButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    _loadedImage?.Dispose();
                    _originalImage?.Dispose();
                    pictureBox1.Image?.Dispose();

                    _loadedImage = new Bitmap(openFileDialog1.FileName);
                    _originalImage = new Bitmap(_loadedImage);
                    pictureBox1.Image = new Bitmap(_originalImage);
                    _originalImageSize = _originalImage.Size;
                    _currentZoom = 1.0f;

                    pictureBox1.SizeMode = checkBox1.Checked
                        ? PictureBoxSizeMode.StretchImage
                        : PictureBoxSizeMode.Normal;

                    ApplyZoom();
                    UpdateStatus("图像加载成功");
                    DatabaseHelper.InsertImageRecord(openFileDialog1.FileName);
                }
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show("无法加载该文件，可能不是有效图像格式。\n\n" + ex.Message, "加载失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("图像加载失败");
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载图像时发生未知错误。\n\n" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("图像加载出错");
            }
            DisplayImageInfo(_originalImage);
            _drawingLayer?.Dispose();
            _drawingLayer = null;
            _isDrawingMode = false;
            _isDrawing = false;
            pictureBox1.Cursor = Cursors.Default;

        }
        private void DisplayImageInfo(Bitmap bmp)
        {
            if (bmp == null) return;

            int colorDepth = Image.GetPixelFormatSize(bmp.PixelFormat);
            float dpiX = bmp.HorizontalResolution;
            float dpiY = bmp.VerticalResolution;

            toolStripStatusLabel1.Text = $"尺寸: {bmp.Width}x{bmp.Height} | 分辨率: {dpiX}x{dpiY} DPI | 色深: {colorDepth}-bit";
        }

        private void LoadImageHistory()
        {
            var dt = DatabaseHelper.GetImageHistory();
            historyListBox.Items.Clear();

            foreach (DataRow row in dt.Rows)
            {
                string display = $"{row["LoadedAt"]}: {row["FilePath"]}";
                historyListBox.Items.Add(display);
            }
        }



        private void backgroundButton_Click(object sender, EventArgs e)
        {
            if (colorDialog1.ShowDialog() == DialogResult.OK)
                pictureBox1.BackColor = colorDialog1.Color;
        }

        private void closeButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // 应用缩放
        private void ApplyZoom()
        {
            if (pictureBox1.Image == null) return;

            // 如果是普通显示模式
            if (pictureBox1.SizeMode == PictureBoxSizeMode.Normal)
            {
                int newWidth = (int)(_originalImageSize.Width * _currentZoom);
                int newHeight = (int)(_originalImageSize.Height * _currentZoom);
                pictureBox1.Size = new Size(newWidth, newHeight);
            }
            // 如果是拉伸模式
            else if (pictureBox1.SizeMode == PictureBoxSizeMode.StretchImage)
            {
                // 在拉伸模式下，调整 Dock 大小以进行缩放
                pictureBox1.Dock = DockStyle.None;  
                pictureBox1.Width = (int)(_originalImageSize.Width * _currentZoom);
                pictureBox1.Height = (int)(_originalImageSize.Height * _currentZoom);
            }
        }

        // 放大
        private void ZoomIn()
        {
            _currentZoom *= 1.1f;
            ApplyZoom();
        }

        // 缩小
        private void ZoomOut()
        {
            _currentZoom /= 1.1f;
            ApplyZoom();
        }
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
                pictureBox1.Dock = DockStyle.Fill;
            }
            else
            {
                pictureBox1.SizeMode = PictureBoxSizeMode.Normal;
                ApplyZoom();
            }
        }

        private Bitmap ApplyGrayscale(Bitmap original)
        {
            Bitmap gray = new Bitmap(original.Width, original.Height);

            for (int y = 0; y < original.Height; y++)
            {
                for (int x = 0; x < original.Width; x++)
                {
                    Color pixel = original.GetPixel(x, y);
                    int grayValue = (int)(pixel.R * 0.3 + pixel.G * 0.59 + pixel.B * 0.11);
                    Color grayColor = Color.FromArgb(grayValue, grayValue, grayValue);
                    gray.SetPixel(x, y, grayColor);
                }
            }
            return gray;
        }
        private Bitmap ApplyInvert(Bitmap original)
        {
            Bitmap inverted = new Bitmap(original.Width, original.Height);

            for (int y = 0; y < original.Height; y++)
            {
                for (int x = 0; x < original.Width; x++)
                {
                    Color pixel = original.GetPixel(x, y);
                    Color invertedColor = Color.FromArgb(255 - pixel.R, 255 - pixel.G, 255 - pixel.B);
                    inverted.SetPixel(x, y, invertedColor);
                }
            }
            return inverted;
        }

        private Bitmap ApplyBlur(Bitmap original)
        {
            Bitmap blurred = new Bitmap(original.Width, original.Height);
            int blurSize = 1; // 1表示3x3范围

            for (int y = blurSize; y < original.Height - blurSize; y++)
            {
                for (int x = blurSize; x < original.Width - blurSize; x++)
                {
                    int r = 0, g = 0, b = 0, count = 0;

                    for (int ky = -blurSize; ky <= blurSize; ky++)
                    {
                        for (int kx = -blurSize; kx <= blurSize; kx++)
                        {
                            Color pixel = original.GetPixel(x + kx, y + ky);
                            r += pixel.R;
                            g += pixel.G;
                            b += pixel.B;
                            count++;
                        }
                    }

                    r /= count; g /= count; b /= count;
                    blurred.SetPixel(x, y, Color.FromArgb(r, g, b));
                }
            }

            return blurred;
        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ApplyFilter(ApplyInvert);
        }


        private void UpdateStatus(string message)
        {
            toolStripStatusLabel1.Text = $"{DateTime.Now:HH:mm:ss} - {message}";
            toolStripProgressBar1.Value = 0;
        }
        private void statusStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

        }

        private void 文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void btnZoomIn_Click(object sender, EventArgs e)
        {
            ZoomIn();
        }

        private void btnZoomOut_Click(object sender, EventArgs e)
        {
            ZoomOut();
        }
        private void FlipImage(RotateFlipType flipType)
        {
            if (pictureBox1.Image == null || _originalImage == null)
                return;

            try
            {
                Bitmap flipped = new Bitmap(_originalImage);
                flipped.RotateFlip(flipType);

                pictureBox1.Image?.Dispose();
                pictureBox1.Image = new Bitmap(flipped);

                _originalImage?.Dispose();
                _originalImage = new Bitmap(flipped);
                _originalImageSize = _originalImage.Size;

                ApplyZoom();
            }
            catch (Exception ex)
            {
                MessageBox.Show("翻转图像时出错。\n\n" + ex.Message, "翻转错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("图像翻转失败");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FlipImage(RotateFlipType.RotateNoneFlipX);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FlipImage(RotateFlipType.RotateNoneFlipY);
        }

        private void 图像自适应ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ApplyFilter(ApplyGrayscale);
        }

        private void 模糊滤镜ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ApplyFilter(ApplyBlur);
        }

        private void 恢复原图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (_imageBeforeFilter != null)
                {
                    _originalImage?.Dispose();
                    pictureBox1.Image?.Dispose();

                    _originalImage = new Bitmap(_imageBeforeFilter);
                    pictureBox1.Image = new Bitmap(_originalImage);
                    _originalImageSize = _originalImage.Size;

                    ApplyZoom();
                    UpdateStatus("恢复原图成功");
                }
                else
                {
                    MessageBox.Show("没有可恢复的原图。", "恢复失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    UpdateStatus("没有原图可恢复");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("恢复原图时发生错误。\n\n" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("恢复原图失败");
            }
        }


        private void ApplyFilter(Func<Bitmap, Bitmap> filterFunc)
        {
            if (_originalImage == null) return;

            try
            {
                _imageBeforeFilter?.Dispose();
                _imageBeforeFilter = new Bitmap(_originalImage);

                Bitmap filtered = filterFunc(_originalImage);
                pictureBox1.Image?.Dispose();
                pictureBox1.Image = new Bitmap(filtered);

                _originalImage?.Dispose();
                _originalImage = new Bitmap(filtered);
                _originalImageSize = _originalImage.Size;

                ApplyZoom();
                UpdateStatus("滤镜应用成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("应用滤镜时发生错误。\n\n" + ex.Message, "滤镜错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("滤镜应用失败");
            }
        }

        private void historyListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (historyListBox.SelectedItem != null)
            {
                string line = historyListBox.SelectedItem.ToString();
                int colonIndex = line.IndexOf(": ");
                if (colonIndex != -1)
                {
                    string path = line.Substring(colonIndex + 2).Trim();
                    if (System.IO.File.Exists(path))
                    {
                        _loadedImage?.Dispose();
                        _originalImage?.Dispose();
                        pictureBox1.Image?.Dispose();

                        _loadedImage = new Bitmap(path);
                        _originalImage = new Bitmap(_loadedImage);
                        pictureBox1.Image = new Bitmap(_originalImage);
                        _originalImageSize = _originalImage.Size;
                        _currentZoom = 1.0f;

                        pictureBox1.SizeMode = checkBox1.Checked
                            ? PictureBoxSizeMode.StretchImage
                            : PictureBoxSizeMode.Normal;

                        ApplyZoom();
                        UpdateStatus("从历史记录加载成功");
                    }
                    else
                    {
                        MessageBox.Show("图像文件不存在。", "加载失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        private void btnToggleHistory_Click(object sender, EventArgs e)
        {
            historyListBox.Visible = !historyListBox.Visible;

            // 可选：根据可见状态同时修改按钮文字
            if (historyListBox.Visible)
                btnToggleHistory.Text = "隐藏历史记录";
            else
                btnToggleHistory.Text = "显示历史记录";

        }

        private void btnCrop_Click(object sender, EventArgs e)
        {
            MessageBox.Show("请按住右键拖动选择区域以裁剪", "提示");
        }

        private void 文件ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {

        }
        private void RotateImage(float angle)
        {
            if (_originalImage == null) return;

            Bitmap rotated = new Bitmap(_originalImage.Width, _originalImage.Height);
            using (Graphics g = Graphics.FromImage(rotated))
            {
                g.Clear(Color.White);
                g.TranslateTransform(_originalImage.Width / 2f, _originalImage.Height / 2f);
                g.RotateTransform(angle);
                g.TranslateTransform(-_originalImage.Width / 2f, -_originalImage.Height / 2f);
                g.DrawImage(_originalImage, new Point(0, 0));
            }

            pictureBox1.Image?.Dispose();
            _originalImage?.Dispose();

            pictureBox1.Image = new Bitmap(rotated);
            _originalImage = new Bitmap(rotated);
            _originalImageSize = _originalImage.Size;

            ApplyZoom();
            UpdateStatus($"旋转 {angle}° 成功");
        }

        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null)
            {
                MessageBox.Show("当前没有图像可以保存。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            using (SaveFileDialog saveDialog = new SaveFileDialog())
            {
                saveDialog.Title = "另存为图像";
                saveDialog.Filter = "PNG 图像 (*.png)|*.png|JPEG 图像 (*.jpg;*.jpeg)|*.jpg;*.jpeg|BMP 图像 (*.bmp)|*.bmp|所有文件 (*.*)|*.*";
                saveDialog.DefaultExt = "png";
                saveDialog.AddExtension = true;
                saveDialog.FileName = "图像";

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        ImageFormat format = ImageFormat.Png;
                        string ext = Path.GetExtension(saveDialog.FileName).ToLower();

                        switch (ext)
                        {
                            case ".jpg":
                            case ".jpeg":
                                format = ImageFormat.Jpeg;
                                break;
                            case ".bmp":
                                format = ImageFormat.Bmp;
                                break;
                            case ".png":
                            default:
                                format = ImageFormat.Png;
                                break;
                        }

                        pictureBox1.Image.Save(saveDialog.FileName, format);
                        UpdateStatus("图像已成功保存到：" + saveDialog.FileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("保存图像时发生错误：\n" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        UpdateStatus("图像保存失败");
                    }
                }
            }
        }

        private void paint_Click(object sender, EventArgs e)
        {
          
        }

        // 修正菜单项功能
        private void 开始绘画ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null)
            {
                MessageBox.Show("请先加载图像", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            _isDrawingMode = true;

            // 创建透明绘图层
            _drawingLayer?.Dispose();
            _drawingLayer = new Bitmap(_originalImage.Width, _originalImage.Height);
            using (Graphics g = Graphics.FromImage(_drawingLayer))
            {
                g.Clear(Color.Transparent);
            }

            // 更改光标为画笔样式
            pictureBox1.Cursor = Cursors.Cross;

            UpdateStatus("绘画模式已激活 - 左键绘图，右键取消");
        }

        private void 保存绘图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!_isDrawingMode || _drawingLayer == null) return;

            try
            {
                // 合并图层到主图像
                using (Graphics g = Graphics.FromImage(_originalImage))
                {
                    g.DrawImage(_drawingLayer, new Point(0, 0));
                }

                // 更新显示
                pictureBox1.Image = new Bitmap(_originalImage);

                // 退出绘画模式
                _isDrawingMode = false;
                _drawingLayer?.Dispose();
                _drawingLayer = null;

                // 恢复光标样式
                pictureBox1.Cursor = Cursors.Default;

                UpdateStatus("绘图已保存并应用到图像");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存绘图时出错: " + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("保存绘图失败");
            }
        }

        private void 取消绘图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _isDrawingMode = false;
            _isDrawing = false;

            // 释放绘图层资源
            _drawingLayer?.Dispose();
            _drawingLayer = null;

            // 恢复光标样式
            pictureBox1.Cursor = Cursors.Default;

            // 刷新显示
            pictureBox1.Invalidate();

            UpdateStatus("已退出绘画模式");
        }
        private void ApplyBackgroundRemoval(Func<Bitmap, Bitmap> removalFunc)
        {
            if (_originalImage == null) return;

            try
            {
                _imageBeforeFilter?.Dispose();
                _imageBeforeFilter = new Bitmap(_originalImage);

                Bitmap removedBackground = removalFunc(_originalImage);
                pictureBox1.Image?.Dispose();
                pictureBox1.Image = new Bitmap(removedBackground);

                _originalImage?.Dispose();
                _originalImage = new Bitmap(removedBackground);
                _originalImageSize = _originalImage.Size;

                ApplyZoom();
                UpdateStatus("背景扣除成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("扣除背景时发生错误。\n\n" + ex.Message, "背景扣除错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("背景扣除失败");
            }
        }

        private Bitmap RemoveSkyBackground(Bitmap originalImage)
        {
            int width = originalImage.Width;
            int height = originalImage.Height;

            Bitmap resultImage = new Bitmap(originalImage);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    Color pixelColor = originalImage.GetPixel(x, y);

                    // 设定天空的颜色范围（这里假设是蓝色调）
                    if (pixelColor.B > 100 && pixelColor.G < 100 && pixelColor.R < 100)
                    {
                        // 将背景（天空部分）设为透明或其他颜色（如白色）
                        resultImage.SetPixel(x, y, Color.White);  // 这里设置为白色背景，当然也可以选择透明
                    }
                }
            }
            return resultImage;
        }

        private void btnRemoveBackground_Click(object sender, EventArgs e)
        {
            // 应用背景扣除
            ApplyBackgroundRemoval(RemoveSkyBackground);
        }

        private void 背景扣除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 使用户选择一个点
            _isSelecting = true;
            pictureBox1.Cursor = Cursors.Cross;  // 将光标变为十字形，提示用户可以选择位置
        }
        private void PictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if (_isSelecting && pictureBox1.Image != null)
            {
                // 获取点击位置的颜色
                Bitmap bmp = (Bitmap)pictureBox1.Image;
                Color selectedColor = bmp.GetPixel(e.X, e.Y);

                // 触发背景扣除操作
                _isSelecting = false;  // 停止选择
                pictureBox1.Cursor = Cursors.Default;  // 恢复光标

                // 使用选中的颜色进行背景扣除
                Bitmap resultImage = RemoveBackgroundByColor(bmp, selectedColor);
                pictureBox1.Image = resultImage;
            }
        }


        private void RemoveBackground(Func<Bitmap, Bitmap> removalFunc)
        {
            if (_originalImage == null) return;

            try
            {
                _imageBeforeFilter?.Dispose();
                _imageBeforeFilter = new Bitmap(_originalImage);

                Bitmap removedBackground = removalFunc(_originalImage);
                pictureBox1.Image?.Dispose();
                pictureBox1.Image = new Bitmap(removedBackground);

                _originalImage?.Dispose();
                _originalImage = new Bitmap(removedBackground);
                _originalImageSize = _originalImage.Size;

                ZoomImage();
                UpdateStatus("背景扣除成功");
            }
            catch (Exception ex)
            {
                MessageBox.Show("扣除背景时发生错误。\n\n" + ex.Message, "背景扣除错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("背景扣除失败");
            }
        }

        private Bitmap RemoveSky(Bitmap originalImage)
        {
            int width = originalImage.Width;
            int height = originalImage.Height;

            Bitmap resultImage = new Bitmap(originalImage);

            int minBlue = 100;
            int maxBlue = 200;
            int minGreen = 100;
            int maxGreen = 180;
            int minRed = 0;
            int maxRed = 150;

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    Color pixelColor = originalImage.GetPixel(x, y);

                    if (pixelColor.B > minBlue && pixelColor.B < maxBlue &&
                        pixelColor.G > minGreen && pixelColor.G < maxGreen &&
                        pixelColor.R > minRed && pixelColor.R < maxRed)
                    {
                        resultImage.SetPixel(x, y, Color.White);
                    }
                }
            }

            return resultImage;
        }

        private void OnRemoveBackgroundClick(object sender, EventArgs e)
        {
            if (_originalImage != null)
            {
                Bitmap result = RemoveSkyBackground(_originalImage);
                pictureBox1.Image = new Bitmap(result);
                _originalImage = new Bitmap(result);
                ZoomImage();
            }
        }

        private void ZoomImage()
        {
            if (_originalImage != null)
            {
                int newWidth = (int)(_originalImage.Width * _currentZoom);
                int newHeight = (int)(_originalImage.Height * _currentZoom);

                pictureBox1.Image = new Bitmap(_originalImage, newWidth, newHeight);
            }
        }

        private void OnHistorySelectionChanged(object sender, EventArgs e)
        {
            if (historyListBox.SelectedItem != null)
            {
                string line = historyListBox.SelectedItem.ToString();
                int colonIndex = line.IndexOf(": ");
                if (colonIndex != -1)
                {
                    string path = line.Substring(colonIndex + 2).Trim();
                    if (System.IO.File.Exists(path))
                    {
                        _loadedImage?.Dispose();
                        _originalImage?.Dispose();
                        pictureBox1.Image?.Dispose();

                        _loadedImage = new Bitmap(path);
                        _originalImage = new Bitmap(_loadedImage);
                        pictureBox1.Image = new Bitmap(_originalImage);
                        _originalImageSize = _originalImage.Size;
                        _currentZoom = 1.0f;

                        pictureBox1.SizeMode = checkBox1.Checked
                            ? PictureBoxSizeMode.StretchImage
                            : PictureBoxSizeMode.Normal;

                        ZoomImage();
                        UpdateStatus("从历史记录加载成功");
                    }
                    else
                    {
                        MessageBox.Show("图像文件不存在。", "加载失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }
        private Bitmap RemoveBackgroundByColor(Bitmap originalImage, Color selectedColor)
        {
            int width = originalImage.Width;
            int height = originalImage.Height;
            Bitmap resultImage = new Bitmap(originalImage);

            BitmapData originalData = originalImage.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
            BitmapData resultData = resultImage.LockBits(new Rectangle(0, 0, width, height),
                ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb);

            int stride = originalData.Stride;
            int bytesPerPixel = 4;
            int byteCount = stride * height;
            byte[] pixelBuffer = new byte[byteCount];
            byte[] resultBuffer = new byte[byteCount];

            Marshal.Copy(originalData.Scan0, pixelBuffer, 0, byteCount);
            originalImage.UnlockBits(originalData);

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    int idx = (y * stride) + (x * bytesPerPixel);
                    byte blue = pixelBuffer[idx];
                    byte green = pixelBuffer[idx + 1];
                    byte red = pixelBuffer[idx + 2];

                    // 比较当前像素和选中的背景颜色
                    if (Math.Abs(blue - selectedColor.B) < 50 &&
                        Math.Abs(green - selectedColor.G) < 50 &&
                        Math.Abs(red - selectedColor.R) < 50)
                    {
                        resultBuffer[idx] = 255;     // Blue
                        resultBuffer[idx + 1] = 255; // Green
                        resultBuffer[idx + 2] = 255; // Red
                        resultBuffer[idx + 3] = 255; // Alpha
                    }
                    else
                    {
                        resultBuffer[idx] = blue;
                        resultBuffer[idx + 1] = green;
                        resultBuffer[idx + 2] = red;
                        resultBuffer[idx + 3] = pixelBuffer[idx + 3];
                    }
                }
            }

            Marshal.Copy(resultBuffer, 0, resultData.Scan0, byteCount);
            resultImage.UnlockBits(resultData);
            return resultImage;
        }

        private void OnToggleHistoryClick(object sender, EventArgs e)
        {
            historyListBox.Visible = !historyListBox.Visible;

            if (historyListBox.Visible)
                btnToggleHistory.Text = "隐藏历史记录";
            else
                btnToggleHistory.Text = "显示历史记录";
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

        }
    }
}
